package com.eff.android.fragment.main.start;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.eff.android.R;
import com.eff.android.api.model.Model;
import com.eff.android.api.model.Setting;
import com.eff.android.fragment.IFragmentCallback;
import com.eff.android.lib.graphics.Base64Convert;
import com.eff.android.lib.helper.EDatabaseHelper;
import com.eff.android.lib.ui.ActionBarController;
import com.eff.android.lib.ui.ECustomDialogHelp;
import com.eff.android.lib.ui.EImageView;
import com.eff.android.lib.ui.ERowView;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

public class EMainFragmentPronounciation extends Fragment
implements TextToSpeech.OnInitListener {

	public static final String TAG = EMainFragmentPronounciation.class.getSimpleName();

    EDatabaseHelper db;
    private List<Model> models;
    Button btnRec;
    private int sizeShowModel;
    
    private final int REQ_CODE_SPEECH_INPUT = 100;
    
    private TextToSpeech tts;
    ImageButton speaker;
    
    Setting settings;
    
    private IFragmentCallback callback;
    Fragment eMainFragmentRecord;
    
    List<ERowView> listRowView;
    int numberOfFalseWord = 0;
    
    List<Integer> check;
	
	public static EMainFragmentPronounciation newInstance(Bundle b) {
		EMainFragmentPronounciation f = new EMainFragmentPronounciation();
		if (b != null){
		    f.setArguments(b);
		}
		return f;
	}

	public static Bundle getArgs() {
		Bundle b = new Bundle();
		b.putString(TAG, TAG);
		return b;
	}

	Animation animate = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		settings = Setting.newInstance();
		check = new ArrayList<Integer>();
		for (int i=0; i<check.size(); i++){
			check.add(0);
		}
		
		sizeShowModel = 10;
		db = new EDatabaseHelper(getActivity().getApplicationContext());
		Log.d("Bien setting", settings.getType().getValue());
		Log.d("Bien setting", "" + settings.getLevel().getValue());

		models = db.getAllModels(sizeShowModel, settings.getSubject(), settings.getType(), settings.getLevel());
		
		initFragments();
		getActivity().getActionBar().show();
		
		animate = AnimationUtils.loadAnimation(getActivity(), R.anim.scaleanimate);		
	}

	private void configActionBar(LayoutInflater inflater) {
		
		View mCustomView = inflater.inflate(R.layout.e_actionbar_default, null);
		btnRec = (Button)mCustomView.findViewById(R.id.btnRec);
		//btnRec.setVisibility(View.VISIBLE);
		final IFragmentCallback call = this.getCallback();
		btnRec.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// Record Process
				promptSpeechInput();
			}
		});
		
		ActionBarController.getInstance().SetActionBarCustomView(getActivity().getActionBar(), mCustomView);
    }
	
	/**
	 * Showing google speech input dialog
	 * */
	private void promptSpeechInput() {
		
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.US);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
				getString(R.string.speech_prompt));
		try {
			startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);			
		} catch (ActivityNotFoundException a) {
			Toast.makeText(getActivity().getApplicationContext(),
					getString(R.string.speech_not_supported),
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Receiving speech input
	 * */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);		

		int flag = -1;
		
		switch (requestCode) {
			case REQ_CODE_SPEECH_INPUT: {
				if (resultCode == getActivity().RESULT_OK && null != data) {
					
					ArrayList<String> result = data
							.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
					String txtSpeechInput = (result.get(0));										
					txtSpeechInput = normalizeFormat(txtSpeechInput);
					
					// Show Speech to text
					Toast.makeText(getActivity().getApplicationContext(),
							result.get(0).toString(),
							Toast.LENGTH_SHORT).show();
					
					// compare text
					for (int i = 0; i < models.size(); i++) {

						if (check.get(i)==0){
						String compare = models.get(i).getVanBan().toString();					
						compare = normalizeFormat(compare);
						
						/*
						Toast.makeText(getActivity().getApplicationContext(),
								"result : " + result.get(0).toString() + " // model : " + compare,
								Toast.LENGTH_SHORT).show();*/
						
						// process true or false						
						if (txtSpeechInput.compareTo(compare) == 0)
						{						
							// found it						
							Toast.makeText(getActivity().getApplicationContext(),
									"Correct!!!",
									Toast.LENGTH_SHORT).show();
							
							// location correct in models => flag != -1
							flag = i;
							check.set(i, 1);
						}	
						}
					}
					
					// not found
					if (flag == -1) {
						numberOfFalseWord++;
						Toast.makeText(getActivity().getApplicationContext(),
								"InCorrect!!!",
								Toast.LENGTH_SHORT).show();
					}
					else {
						updateListModel(flag);
					}
						
				}
				break;
			}	

		}
	}
	
	// Update list Model Here
	private void updateListModel(int locationRemove) {
		
		// Thay the doan toast bang cap nhat moi listView nha
		RefreshListView(locationRemove);
	}
	
	// Normalize true format to compare
	private String normalizeFormat(String str) {
		
		if (str.length() > 0 && (str.charAt(str.length()-1) == '.'
	    		|| str.charAt(str.length()-1) == ',' || str.charAt(str.length()-1) == '?'
	    		|| str.charAt(str.length()-1) == '!')) {
			str = str.substring(0, str.length()-1);
		}
			
	    if (str.length() > 0 && (str.charAt(str.length()-2) == '.'
	    		|| str.charAt(str.length()-2) == ',' || str.charAt(str.length()-2) == '?'
	    		|| str.charAt(str.length()-2) == '!')) {
	      str = str.substring(0, str.length()-2);
	    }	        
	    
	    return str.toLowerCase();
	}
	
	private void initFragments() {
		eMainFragmentRecord = EMainFragmentStartRecord.newInstance(this.getArguments());
		((EMainFragmentStartRecord) eMainFragmentRecord).setCallback(this.callback);
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		configActionBar(inflater);
		
		View v = inflater.inflate(R.layout.e_frm_main_start_pronunciation, container, false);
		Log.d("Models Count: ", String.valueOf(models.size()));
		initViews(v);
		
		return v;
    }
	
	private void initRowItems(View v){
		//rowItems = new ArrayList<ERowItem>();
		Base64Convert convertor = new Base64Convert();
		
        for (int i = 0; i < sizeShowModel; i=i+2) {
        	//Tao Bitmap dong nay nha
        	Bitmap iconLeft = convertor.Decompress(models.get(i).getUriHinh(), Base64.DEFAULT);
        	Bitmap iconRight = convertor.Decompress(models.get(i+1).getUriHinh(), Base64.DEFAULT);
        	
           // ERowItem items = new ERowItem(models.get(i).getVanBan(), icon);
            //rowItems.add(items); Add items o day
        	EImageView left = new EImageView(v.getContext(), models.get(i).getVanBan(), iconLeft);
        	EImageView right = new EImageView(v.getContext(), models.get(i+1).getVanBan(), iconRight);
        	ERowView rowView = new ERowView(v.getContext(), left, right);
        	listRowView.add(rowView);      	
        }
	}

	private void initViews(View v) {
		
		listRowView = new ArrayList<ERowView>();
		initRowItems(v);
		LinearLayout layout = (LinearLayout)v.findViewById(R.id.imageViewLayout);
		for(int i=0; i<listRowView.size(); i++){
			layout.addView(listRowView.get(i));
			final int k = 2*i;
			
			// Click on Image
			listRowView.get(i).getImageViewLeft().setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					ShowMenuHelper(v, k);
				}
			});
			
			listRowView.get(i).getImageViewRight().setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					ShowMenuHelper(v, k+1);
				}
			});
			
			// Click on Text
			listRowView.get(i).getImageViewLeft().getWordText().setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					ShowMenuHelper(v, k);
				}
			});
			
			listRowView.get(i).getImageViewRight().getWordText().setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					ShowMenuHelper(v, k+1);
				}
			});
		}
	}
	
	/**
	 * Tinh toan lai hieu ung va cap nhat lai hinh anh
	 * @param index
	 * 	vi tri cua tu trong listmodel
	 *  Tat ca chia cho 2
	 *  	Phan nguyen: row id
	 *  	Phan du: 0: left 1: right
	 */
	private void RefreshListView(int index){
		
		//if index = -1 : End function
		if(index == -1)
			return;

		Log.i("Recode", String.valueOf(index));
		int iRow = index / 2;
		EImageView selected = null;
		
		switch(index % 2)
		{
		case 0:
			Log.i("Recode", "left");
			selected = this.listRowView.get(iRow).getImageViewLeft();
			selected.startAnimation(animate);
			selected.setVisibility(View.GONE);
			break;
		case 1:
			Log.i("Recode", "right");
			selected = this.listRowView.get(iRow).getImageViewRight();
			selected.startAnimation(animate);
			selected.setVisibility(View.GONE);
			break;
		default:
			break;
		}

		if (CheckEnd()){
			Bundle args = new Bundle();
			args.putInt("numberOfFalseWord", numberOfFalseWord);
			eMainFragmentRecord.setArguments(args);
			this.callback.gotoNextPage(eMainFragmentRecord);
		}
	}
	
	private boolean CheckEnd() {
		for (int i=0; i<check.size();i++){
			if (check.get(i)==0)
				return false;
		}
		return true;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		
		// Don't forget to shutdown!
				if (tts != null) {
					tts.stop();
					tts.shutdown();
				}
				
		getActivity().getActionBar().hide();
		super.onDestroy();
	}

	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub

		if (status == TextToSpeech.SUCCESS) {

			int result = tts.setLanguage(Locale.US);

			// tts.setPitch(5); // set pitch level

			// tts.setSpeechRate(2); // set speech speed rate

			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				Log.e("TTS", "Language is not supported");
			} else {
				speaker.setEnabled(true);
				speakOut("");
			}

		} else {
			Log.e("TTS", "Initilization Failed");
		}

	}
	
	private void speakOut(String text) {

		tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
	}
	
	public IFragmentCallback getCallback() {
		return callback;
	}

	public void setCallback(IFragmentCallback callback) {
		this.callback = callback;
	}

	public void ShowMenuHelper(View view, int id) {
		final int pos = id;
		String mean = "";
		String trans = "";
		
		// Get mean and trans
		for (int i = 0; i < models.size(); i++) {
			
			if (i == pos) {
				mean = models.get(i).getYNghia().toString();
				trans = models.get(i).getPhienAmQuocTe().toString();
			}			
		}				
		
		final ECustomDialogHelp dialog = new ECustomDialogHelp(view.getContext());		
		
		// Show Mean and trans
		TextView tvMean = (TextView) dialog.findViewById(R.id.meanTextView);
		tvMean.setText(mean);
		TextView tvTrans = (TextView) dialog.findViewById(R.id.transcriptionTextView);
		tvTrans.setText(trans);
		
		// Show dialog
		dialog.show();
		
		tts = new TextToSpeech(getActivity(), this);
		
		speaker = (ImageButton) dialog.findViewById(R.id.btnSpeaker);
	    speaker.setOnClickListener(new View.OnClickListener() {

	    String text = "";	    
	    
	    // Process SpeakOut
		@Override
		public void onClick(View arg0) {
			
			/*
			Toast.makeText(getActivity().getApplicationContext(),
					String.valueOf(pos),
					Toast.LENGTH_SHORT).show();*/
						
			for (int i = 0; i < models.size(); i++) {				
				if (i == pos) {
					text = models.get(i).getVanBan().toString();
				}							
			}
			
			// Speak Out
			speakOut(text);
		}

	});
	}
	
}
